package com.lagou.web;

import com.lagou.domain.LoginResponse;
import com.lagou.domain.Student;
import com.lagou.service.AddService;
import com.lagou.util.GetPostJson;
import com.lagou.util.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

/**
 * 添加学生的控制层
 */
public class AddStudentController extends HttpServlet {
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req,resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//获取post请求的json请求体
		String jsonPost = GetPostJson.getPostJson(req);
		// 将请求体的json字符串转为studnet对象
		Student student = JsonUtil.json2Object(jsonPost,Student.class);
		try {
			//调用添加学生的service方法
			AddService.addStudentService(student);
			//此时没报异常，把响应结果封装成json对象返回给客户端，200表示添加成功
			resp.getWriter().write(JsonUtil.object2Json(new LoginResponse(200,"添加成功")));
		} catch (SQLException e) {
			e.printStackTrace();
			//报异常，把添加失败返回给客户端
			resp.getWriter().write(JsonUtil.object2Json(new LoginResponse(-1,"添加失败")));

		}
	}
}
